package cn.iune.erp.sale;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.persistence.NoResultException;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.justep.baas.Utils;
import com.justep.baas.data.DataUtils;
import com.justep.baas.data.Row;
import com.justep.baas.data.Table;
import com.justep.baas.data.Transform;

import cn.iune.common.base.BaseJPAImpl;


@Repository
public class SaleOrderDetailDaoJPAImpl extends BaseJPAImpl<SaleOrderDetail> implements ISaleOrderDetailDao {

//	private final Logger log = LoggerFactory.getLogger(SaleOrderDetailDaoJPAImpl.class);

//	private String kSql;
//	@PersistenceContext 
//	private EntityManager em ;


	
	@Override
	public void insert(SaleOrderDetail obj) {
		em.persist(obj);
	}

	@Override
	public void delete(String fID) {
		em.remove(em.getReference(SaleOrderDetail.class, fID));
	}

	@Override
	public SaleOrderDetail update(SaleOrderDetail obj) {
		SaleOrderDetail objNew = em.merge(obj);
		return objNew;
	}

	@Override
	public SaleOrderDetail getByID(String fID) {
		SaleOrderDetail singleResult = em.find(SaleOrderDetail.class, fID);
		return singleResult;
	}

	@Override
	public List<SaleOrderDetail> getAll() {
		Query query = em.createNamedQuery("SaleOrderDetail.findAll");
		@SuppressWarnings("unchecked")
		List<SaleOrderDetail> resultList = query.getResultList();
		return resultList;
	}

	@Override
	public List<SaleOrderDetail> getByMasterID(String fMasterID) {
		// TODO Auto-generated method stub
		String kSql="SELECT SaleOrderDetail FROM SaleOrderDetail SaleOrderDetail WHERE SaleOrderDetail.fMasterID=:fMasterID ORDER BY SaleOrderDetail.serialNo";
		Query query = em.createQuery(kSql);
		query.setParameter("fMasterID", fMasterID);
		@SuppressWarnings("unchecked")
		List<SaleOrderDetail> resultList = query.getResultList();
		return resultList;
	}

	@Override
	public SaleOrderDetail getByNo(String orderNo, String serialNo, String enterpriseNo) {
		//1、定义sql语句
		String kSql="SELECT SaleOrderDetail FROM SaleOrderDetail SaleOrderDetail "
				+ " WHERE ( SaleOrderDetail.orderNo = :orderNo ) "
				+ " AND ( SaleOrderDetail.serialNo = :serialNo ) "
				+ " AND ( SaleOrderDetail.enterpriseNo = :enterpriseNo ) "
				;

		Query query = em.createQuery(kSql);
		query.setParameter("orderNo", orderNo);
		query.setParameter("serialNo", serialNo);
		query.setParameter("enterpriseNo", enterpriseNo);
		SaleOrderDetail singleResult = null;
		try{
			singleResult = (SaleOrderDetail) query.getSingleResult();
		}catch(NoResultException e){
			//捕获没有结果的异常
			//避免抛出异常而中断对前台的相应。
		}finally{
		}
		return singleResult;
	}

	@Override
	public List<SaleOrderDetail> getByCustomerID(String customerID) {
		// TODO Auto-generated method stub
		String kSql="SELECT SaleOrderDetail FROM SaleOrderDetail SaleOrderDetail WHERE SaleOrderDetail.customerID=:customerID ORDER BY SaleOrderDetail.serialNo";
		Query query = em.createQuery(kSql);
		query.setParameter("customerID", customerID);
		@SuppressWarnings("unchecked")
		List<SaleOrderDetail> resultList = query.getResultList();
		return resultList;
	}

//	@Override
//	public List<SaleOrderDetail> getByGuestNumber(String guestNumber/* , String factoryID */, String enterpriseNo) {
//		String kSql="SELECT SaleOrderDetail "
//				+ " FROM SaleOrderDetail SaleOrderDetail "
//				+ " WHERE SaleOrderDetail.guestNumber=:guestNumber "
//				+ " AND SaleOrderDetail.enterpriseNo=:enterpriseNo "
//				+ " ORDER BY SaleOrderDetail.orderNo,SaleOrderDetail.serialNo";
//		Query query = em.createQuery(kSql);
//		query.setParameter("guestNumber", guestNumber);
//		query.setParameter("enterpriseNo", enterpriseNo);
//		@SuppressWarnings("unchecked")
//		List<SaleOrderDetail> resultList = query.getResultList();
//		return resultList;
//	}

	@Override
	public List<SaleOrderDetail> getByStorageNo(String storageNo, String factoryNo, String enterpriseNo) {
		// TODO Auto-generated method stub
		String kSql="SELECT SaleOrderDetail "
				+ " FROM SaleOrderDetail SaleOrderDetail "
				+ " WHERE SaleOrderDetail.storageNo=:storageNo "
				+ " AND SaleOrderDetail.factoryNo=:factoryNo "
				+ " AND SaleOrderDetail.enterpriseNo=:enterpriseNo "
				;
		Query query = em.createQuery(kSql);
		query.setParameter("storageNo", storageNo);
		query.setParameter("factoryNo", factoryNo);
		query.setParameter("enterpriseNo", enterpriseNo);
		@SuppressWarnings("unchecked")
		List<SaleOrderDetail> resultList = query.getResultList();
		return resultList;
	}

	/*
	@Override
	public int save(JSONObject object) throws Throwable {
		// TODO Auto-generated method stub
		// JSON转换Table
		Table table = Transform.jsonToTable(object);
		List<Row> list = table.getRows();
		for(Row row : list){
			JSONObject javaObject= Transform.rowToJavaObject(table, row);
			SaleOrderDetail obj = JSON.toJavaObject(javaObject, SaleOrderDetail.class);
			if(RowState.NEW.equals(obj.getRowState())){
				this.insert(obj);
			}
			if(RowState.EDIT.equals(obj.getRowState())){
				this.update(obj);
			}
			if(RowState.DELETE.equals(obj.getRowState())){
				this.delete(obj.getfID());
			}
		}
		return 0;
	}
	 */

	
	@Override
	public JSONObject create(JSONObject data) {
		//缺省列
		String defColstr = Utils.getDefCols(SaleOrderDetail.class);
		data.put("defColstr", defColstr);
		return Utils.newData(data);

	}

	@Override
	public JSONObject query(JSONObject data) throws SQLException {
		
		// 获取参数
		JSONObject columns = data.getJSONObject("columns"); // 列定义
		String orderBy = data.getString("orderBy"); // 排序
		Integer limit = data.getInteger("limit"); // 分页查询的行数
		Integer offset = data.getInteger("offset"); // 分页查询的行偏移
		String search = data.getString("search"); // 检索关键字
		String filter = data.getString("filter"); // 过滤条件
		String id = data.getString("id");
		String fMasterID = data.getString("fMasterID");

		//		log.info("limit-->"+limit);
//		log.info("offset-->"+offset);
//		log.info("filters-->"+filters);
//		log.info("sqlParams-->"+params);
		
		String format = "SELECT %s FROM %s %s %s ";
//		String format = "SELECT SaleOrderDetail FROM SaleOrderDetail SaleOrderDetail %s %s ";
		String select = "SaleOrderDetail.*"
				+ ",if(SaleOrderDetail.itemProperty is null,SaleOrderDetail.itemName,CONCAT(SaleOrderDetail.itemName,'【',SaleOrderDetail.itemProperty,'】')) as itemDescribe"

				//待发货数量
				+ ",(SaleOrderDetail.itemAmount - SaleOrderDetail.pickItemIng - SaleOrderDetail.pickItemAmount) as pendingQuantity"
				+ ",(SaleOrderDetail.pieceQuantity - SaleOrderDetail.pickPiece) as pendingPiece"

				+ ",FileItem.qualityType"
				+ ",FileItem.qualityTypeLabel"
				+ ",FileItem.batchNo"
				+ ",FileItem.qualityPeriod"
				+ ",FileItem.validDays"
				+ ",FileItem.checkoutAgainDays"
				+ ",FileItem.storeNo"
				+ ",FileItem.images"
				+ ",FileItem.barcode"
				
				+ ",FileItem.process"
				+ ",FileItem.processLabel"
				
//				+ ",FileItem.qualityStatus"
//				+ ",FileItem.qualityStatusLabel"
				;
		
//		String from = "SaleOrderDetail SaleOrderDetail";
		String from = "SaleOrderDetail SaleOrderDetail LEFT JOIN FileItem FileItem ON (FileItem.fID = SaleOrderDetail.itemID)"
				;

		
		// 存放SQL中的参数值
		List<Object> sqlParams = new ArrayList<Object>();
		// 存放SQL中的过滤条件
		List<String> filters = new ArrayList<String>();
		
		if (Utils.isNotEmptyString(search)) {
			// 增加过滤条件
			filters.add("SaleOrderDetail.serialNo LIKE ? OR SaleOrderDetail.itemName LIKE ? OR SaleOrderDetail.comments LIKE ? ");
			// 检索关键字中如果没有%，则前后自动加%
			search = (search.indexOf("%") != -1) ? search : "%" + search + "%";
			// sqlParams的参数个数和顺序必须与过滤条件的?相匹配 
			for (int i = 0; i < 3; i++) {
				sqlParams.add(search);
			}
		}
		
		//处理过滤条件
		if (Utils.isNotEmptyString(filter)) {
			filters.add(filter);
		}
		//处理id
		if (Utils.isNotEmptyString(id)) {
			filters.add("fID='"+id+"'");
		}
		//处理fMasterID
		if (Utils.isNotEmptyString(fMasterID)) {
			filters.add("fMasterID='"+fMasterID+"'");
		}
		
		//处理条件过滤
		JSONArray filterList = data.getJSONArray("filters"); // 列定义
		if(filterList!=null && filterList.size()>0){
			for(int i=0;i<filterList.size();i++){
				JSONObject jsonFilter = filterList.getJSONObject(i);
//				System.out.println("jsonFilter.getString(\"filter\")-->"+jsonFilter.getString("filter"));
				filters.add(jsonFilter.getString("filter"));
			}
		}
		
		String where = "";
		
		if(filters != null && filters.size() > 0){
			if(where.indexOf("WHERE")== -1){
				//不包含WHERE关键字
				where = "WHERE " + DataUtils.arrayJoin(filters.toArray(), "(%s)", " AND ");
			}else{
				//已包含
				where = where + " AND " + DataUtils.arrayJoin(filters.toArray(), "(%s)", " AND ");
			}
		}
		

		//orderBy = "sortNo ASC";
//		String where = (filters != null && filters.size() > 0) ? " WHERE " + CommonService.arrayJoin(filters.toArray(), "(%s)", " AND ") : "";
		orderBy = Utils.isNotEmptyString(orderBy) ? " ORDER BY " + orderBy : "";
		
		String sql = String.format(format, select, from, where, orderBy);
		
//		System.out.println(sql);
		
//		Connection conn = DataUtils.getConnection(DataUtils.DATASOURCE_1);
		Connection conn = super.getConnection();
		String sqlTotal = String.format(format, "COUNT(*)", from, where, "");
		Object total = DataUtils.getValueBySQL(conn, sqlTotal, sqlParams);
		//SELECT SaleOrderDetail.fID FROM SaleOrderDetail SaleOrderDetail    LIMIT 0,-1//为-1时报错。
		if(limit==-1){
			limit = Integer.parseInt(total.toString());
		}
		
//		Table table = DataUtils.queryData(conn, tableName, columns, filters, orderBy, params, offset, limit);
		Table table = DataUtils.queryData(conn, sql, sqlParams, columns, offset, limit);

		table.setTotal(Integer.parseInt(total.toString()));
		JSONObject json = Transform.tableToJson(table);
		//////////////////////////////////自定义聚合数据/////////////////////////////////
		//////////////////////////////////////////////////////////////////////////////
		String aggregateSelect = "";
		
		JSONObject aggregateColumns = data.getJSONObject("aggregateColumns"); // 聚合列定义
//		System.out.println("aggregateColumns-->"+aggregateColumns);
		if(aggregateColumns!=null){
			
			Set<String> keys = aggregateColumns.keySet();
			int index = 0;
			for(String key:keys){
				if(index==0){
					aggregateSelect = aggregateSelect + "SUM(" + key + ") as " + aggregateColumns.getJSONObject(key).getString("name");
				}else{
					aggregateSelect = aggregateSelect + ",SUM(" + key + ") as " + aggregateColumns.getJSONObject(key).getString("name");
				}
				
				index++;
			}
			
//			aggregateSelect = "SUM(StorageItem.quantityL) as sumQuantityL,SUM(CONVERT(FileItem.costingAmountPer*StorageItem.quantityL,decimal(38,2))) as sumCostingAmount,SUM(StorageItem.pieceQuantityL) as sumPieceQuantityL";
			
		}
		
//		String aggregate = data.getString("aggregate");
//		if(aggregate!=null){
//			if(aggregateSelect.equals("")){
//				aggregateSelect = aggregate;
//			}else{
//				aggregateSelect = aggregateSelect + "," + aggregate;
//			}
//		}
		
//		System.out.println("aggregateSelect-->"+aggregateSelect);
		
		if(!aggregateSelect.equals("")){
			//如果select不为空
			
			String aggregateSql = String.format(format, aggregateSelect, from, where, "");
//			System.out.println("aggregateSql-->"+aggregateSql);
			Table aggregateTable = DataUtils.queryData(conn, aggregateSql, sqlParams, aggregateColumns, 0, table.getTotal());
//			Row row = aggregateTable.getRows().get(0);
//			JSONObject aggregateValues = Transform.rowToJson(aggregateTable, row);
			JSONObject jo = Transform.tableToJson(aggregateTable);
			JSONArray jarray = jo.getJSONArray("rows");
			JSONObject aggregateValues = new JSONObject();
			if(jarray.size()>0){
				aggregateValues = jarray.getJSONObject(0);
			}
//			System.out.println("aggregateValues-->"+aggregateValues);
			//jb-->{"userdata":{"recordState":"none"},"costingAmount":{"value":"599517613.43"},"costingAmountPer":{"value":"59957.893727"}}
			json.put("aggregateValues", aggregateValues);
		}
		//////////////////////////////////////////////////////////////////////////////////
		//////////////////////////////////////////////////////////////////////////////////
		//关闭连接
		conn.close();
		
		return json;
	}


	@Override
	public JSONObject querySimple(JSONObject data) throws SQLException {
		
		// 获取参数
		JSONObject columns = data.getJSONObject("columns"); // 列定义
		String orderBy = data.getString("orderBy"); // 排序
		Integer limit = data.getInteger("limit"); // 分页查询的行数
		Integer offset = data.getInteger("offset"); // 分页查询的行偏移
		String search = data.getString("search"); // 检索关键字
		String filter = data.getString("filter"); // 过滤条件
		String id = data.getString("id");
		String fMasterID = data.getString("fMasterID");

//		log.info("limit-->"+limit);
//		log.info("offset-->"+offset);
//		log.info("filters-->"+filters);
//		log.info("sqlParams-->"+params);
		
		String format = "SELECT %s FROM %s %s %s ";
//		String format = "SELECT SaleOrderDetail FROM SaleOrderDetail SaleOrderDetail %s %s ";
		String select = "SaleOrderDetail.*"
				+ ",if(SaleOrderDetail.itemProperty is null,SaleOrderDetail.itemName,CONCAT(SaleOrderDetail.itemName,'【',SaleOrderDetail.itemProperty,'】')) as itemDescribe"

				//待发货数量
				+ ",(SaleOrderDetail.itemAmount - SaleOrderDetail.pickItemIng - SaleOrderDetail.pickItemAmount) as pendingQuantity"
				+ ",(SaleOrderDetail.pieceQuantity - SaleOrderDetail.pickPiece) as pendingPiece"

				+ ",FileItem.qualityType"
				+ ",FileItem.qualityTypeLabel"
				+ ",FileItem.batchNo"
				+ ",FileItem.qualityPeriod"
				+ ",FileItem.validDays"
				+ ",FileItem.checkoutAgainDays"
				+ ",FileItem.storeNo"
				+ ",FileItem.images"
				+ ",FileItem.barcode"
				
				+ ",FileItem.process"
				+ ",FileItem.processLabel"
				
//				+ ",FileItem.qualityStatus"
//				+ ",FileItem.qualityStatusLabel"

				+ ",SaleOrder.guestNumber"
				+ ",SaleOrder.ssID"
				+ ",SaleOrder.handling"
				+ ",SaleOrder.handlingLabel"
				+ ",SaleOrder.packFlag"

				;
		
//		String from = "SaleOrderDetail SaleOrderDetail";
		String from = "SaleOrderDetail SaleOrderDetail LEFT JOIN FileItem FileItem ON (FileItem.fID = SaleOrderDetail.itemID)"
				+ "  LEFT JOIN SaleOrder SaleOrder ON (SaleOrder.fID = SaleOrderDetail.fMasterID)"
				;

		
		// 存放SQL中的参数值
		List<Object> sqlParams = new ArrayList<Object>();
		// 存放SQL中的过滤条件
		List<String> filters = new ArrayList<String>();
		
		if (Utils.isNotEmptyString(search)) {
			// 增加过滤条件
			filters.add("SaleOrderDetail.serialNo LIKE ? OR SaleOrderDetail.itemName LIKE ? OR SaleOrderDetail.comments LIKE ? ");
			// 检索关键字中如果没有%，则前后自动加%
			search = (search.indexOf("%") != -1) ? search : "%" + search + "%";
			// sqlParams的参数个数和顺序必须与过滤条件的?相匹配 
			for (int i = 0; i < 3; i++) {
				sqlParams.add(search);
			}
		}
		
		//处理过滤条件
		if (Utils.isNotEmptyString(filter)) {
			filters.add(filter);
		}
		//处理id
		if (Utils.isNotEmptyString(id)) {
			filters.add("fID='"+id+"'");
		}
		//处理fMasterID
		if (Utils.isNotEmptyString(fMasterID)) {
			filters.add("fMasterID='"+fMasterID+"'");
		}
		
		//处理条件过滤
		JSONArray filterList = data.getJSONArray("filters"); // 列定义
		if(filterList!=null && filterList.size()>0){
			for(int i=0;i<filterList.size();i++){
				JSONObject jsonFilter = filterList.getJSONObject(i);
//				System.out.println("jsonFilter.getString(\"filter\")-->"+jsonFilter.getString("filter"));
				filters.add(jsonFilter.getString("filter"));
			}
		}
		
		String where = "";
		
		if(filters != null && filters.size() > 0){
			if(where.indexOf("WHERE")== -1){
				//不包含WHERE关键字
				where = "WHERE " + DataUtils.arrayJoin(filters.toArray(), "(%s)", " AND ");
			}else{
				//已包含
				where = where + " AND " + DataUtils.arrayJoin(filters.toArray(), "(%s)", " AND ");
			}
		}
		

		//orderBy = "sortNo ASC";
//		String where = (filters != null && filters.size() > 0) ? " WHERE " + CommonService.arrayJoin(filters.toArray(), "(%s)", " AND ") : "";
		orderBy = Utils.isNotEmptyString(orderBy) ? " ORDER BY " + orderBy : "";
		
		String sql = String.format(format, select, from, where, orderBy);
		
//		System.out.println(sql);
		
//		Connection conn = DataUtils.getConnection(DataUtils.DATASOURCE_1);
		Connection conn = super.getConnection();
		String sqlTotal = String.format(format, "COUNT(*)", from, where, "");
		Object total = DataUtils.getValueBySQL(conn, sqlTotal, sqlParams);
		//SELECT SaleOrderDetail.fID FROM SaleOrderDetail SaleOrderDetail    LIMIT 0,-1//为-1时报错。
		if(limit==-1){
			limit = Integer.parseInt(total.toString());
		}
		
//		Table table = DataUtils.queryData(conn, tableName, columns, filters, orderBy, params, offset, limit);
		Table table = DataUtils.queryData(conn, sql, sqlParams, columns, offset, limit);

		//关闭连接
		conn.close();

		table.setTotal(Integer.parseInt(total.toString()));
		table.setOffset(offset);
		table.setTableName("SaleOrderDetail");
		
		//JSONObject json = Transform.tableToJson(table);
		
		JSONArray arrayItem = new JSONArray();

		List<Row> list = table.getRows();
		for(Row row : list){
			JSONObject javaObject= Transform.rowToJavaObject(table, row);
			SaleOrderDetail obj = JSON.toJavaObject(javaObject, SaleOrderDetail.class);
			
			arrayItem.add(obj);
		}
		
		JSONObject json = new JSONObject();
		
		json.put("data", arrayItem);
		json.put("total", Integer.parseInt(total.toString()));
		json.put("code", 0);
		json.put("msg", "success");
		
		return json;
		
	}

	
}
